﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BrnMall.Manager.Manager.Product
{
    /// <summary>
    /// 商品管理
    /// </summary>
    public static class ProductManager
    {
        /// <summary>
        /// 批量更新商品销量
        /// </summary>
        /// <param name="pids"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        public static void UpdateProductSaleCount(string pids, int min,int max)
        {
            using (var db = new QDMallDatabase())
            {
                var sb = new StringBuilder();
                var ids = pids.Split(new []{ ','},StringSplitOptions.RemoveEmptyEntries);
                var random=new Random();
                foreach (var id in ids)
                {
                    var count=random.Next(min,max);
                    
                    sb.AppendLine($"update bma_products set salecount={count} where pid={id}");
                }
                if (sb.Length > 0)
                    db.Execute(sb.ToString());
            }
        }
        /// <summary>
        /// 清除轮播图的设置
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="pimgid"></param>
        public static void ClearProductBannerImageSet(int pid, int pimgid,int op)
        {
            using (var db = new QDMallDatabase())
            {
                db.Execute("UPDATE [bma_productimages] SET [isbanner]=@0 WHERE [pimgid]=@1",op,pimgid);
                db.Execute("UPDATE [bma_products] SET [bannerimg]='' WHERE [pid]=@0", pid);
            }
        }

        public static void UpdateRealSaleCount(IDictionary<int, int> pidAndSaleCounts)
        {
            using (var db = new QDMallDatabase())
            {
                var sql=new StringBuilder(100);
                foreach (var ps in pidAndSaleCounts)
                {
                    sql.AppendFormat(" update bma_products set salecount={0} where pid={1} ", ps.Value, ps.Key);
                }
                db.Execute(sql.ToString());
            }
        }

        public static int CaculateRealSaleCount(int pid)
        {
            using (var db = new QDMallDatabase())
            {
                return db.ExecuteScalar<int>(
                    $"select count(a.realcount) from dbo.bma_orderproducts a left join dbo.bma_orders b on a.oid=b.oid where a.pid={pid} and b.orderstate=120 ");
            }
        }

    }
}
